package com.xcc.shopanim.olda;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.viewpager.widget.ViewPager;

import com.gigamole.infinitecycleviewpager.HorizontalInfiniteCycleViewPager;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.xcc.shopanim.AppConstant;
import com.xcc.shopanim.BaseFragment;
import com.xcc.shopanim.MiniLivePhotoFragment;
import com.xcc.shopanim.R;
import com.xcc.shopanim.adapter.ViewPagerAdapter;
import com.xcc.shopanim.mode.BannerMode;
import com.xcc.shopanim.mode.ImageMode;
import com.xcc.shopanim.mode.MainLiveVideoGroupMode;
import com.xcc.shopanim.mode.NewMainVideoMode;
import com.xcc.shopanim.widget.VerticalDrawerLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MainLiveFragment extends BaseFragment implements OnRefreshListener, LayoutDrawerViewHolder.OnLayoutDrawerListener {
    @BindView(R.id.smartLayout)
    SmartRefreshLayout smartLayout;
    @BindView(R.id.horizontalViewPager)
    HorizontalInfiniteCycleViewPager horizontalViewPager;
    @BindView(R.id.layoutContent)
    View layoutContent;
    @BindView(R.id.layoutDrawer)
    VerticalDrawerLayout layoutDrawer;
    private LayoutDrawerViewHolder drawerViewHolder;
    private List<NewMainVideoMode> modeList;
    private List<BaseFragment> fragmentList;
    private ViewPagerAdapter pagerAdapter;
    private float contentOffset;

    public static MainLiveFragment newInstance() {
        MainLiveFragment fragment = new MainLiveFragment();
        /*Bundle bundle = new Bundle();
        bundle.putInt("liveType", liveType);
        fragment.setArguments(bundle);*/
        return fragment;
    }

    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_main_live, null);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        modeList = new ArrayList<>();
        fragmentList = new ArrayList<>();
        pagerAdapter = new ViewPagerAdapter(getChildFragmentManager(), fragmentList);
        horizontalViewPager.setAdapter(pagerAdapter);
        horizontalViewPager.setOffscreenPageLimit(5);

        smartLayout.setOnRefreshListener(this);
        smartLayout.setEnableLoadMore(false);

        isInit = true;
        stateChange();
        drawerViewHolder = new LayoutDrawerViewHolder(getActivity(), layoutDrawer, modeList)
                .setOnLayoutDrawerListener(this);
        layoutDrawer.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                layoutDrawer.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                int height = layoutContent.getHeight();
                if (height > 0) {
                    ViewGroup.LayoutParams layoutParams = layoutDrawer.getLayoutParams();
                    if (layoutParams != null) {
                        layoutParams.height = height;
                        layoutDrawer.setLayoutParams(layoutParams);
                    }
                }
            }
        });
        horizontalViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                drawerViewHolder.onPageSelected(position);
            }
        });
    }

    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        this.isVisibleToUser = isVisibleToUser;
        stateChange();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        stateChange();
    }

    @Override
    public void onResume() {
        super.onResume();
        stateChange();
    }

    @Override
    public void onPause() {
        super.onPause();
        stateChange();
    }

    private void stateChange() {
        boolean isShow;
        if (isPause || hidden) isShow = false;
        else isShow = isVisibleToUser && isInit;
        if (isShow) {
            if (isViewResume) return;
            viewResume();
        } else {
            if (isViewResume) viewPause();
        }
    }

    private boolean canClick = true;
    private boolean canSetClick;
    private int clickIdx;
    private boolean isViewResume;
    private boolean isVisibleToUser;
    private boolean isInit;

    private void viewResume() {
        isViewResume = true;
        if (modeList.size() == 0) smartLayout.autoRefresh();
        if (fragmentList.size() > 0) {
            int currentItem = horizontalViewPager.getCurrentItem();
            BaseFragment fragment = fragmentList.get(currentItem);
            fragment.onHiddenChanged(false);
        }
    }

    private void viewPause() {
        isViewResume = false;
        if (fragmentList.size() > 0) {
            int currentItem = horizontalViewPager.getCurrentItem();
            BaseFragment fragment = fragmentList.get(currentItem);
            fragment.onHiddenChanged(true);
        }
    }

    @Override
    public void onDestroyView() {
        if (drawerViewHolder != null) drawerViewHolder.onDestroy();
        drawerViewHolder = null;
        /*RoomRequestManage.getInstance(RoomRequestManage.RequestType.DefaultType)
                .removeManageView(this);*/
        super.onDestroyView();
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        MainLiveVideoGroupMode videoGroupMode = new MainLiveVideoGroupMode();
        List<NewMainVideoMode> videoModeList = videoGroupMode.getVideoModeList();
        String[] urls = {AppConstant.ImgDebugUrl,
                AppConstant.ImgDebugUrl2,
                AppConstant.ImgDebugUrl3,
                AppConstant.ImgDebugUrl4,
                AppConstant.ImgDebugUrl5,
                AppConstant.ImgDebugUrl6,
                AppConstant.ImgDebugUrl7,
                AppConstant.ImgDebugUrl8,
                AppConstant.ImgDebugUrl9,
                AppConstant.ImgDebugUrl10};
        for (int i = 0; i < urls.length; i++) {
            BannerMode bannerMode = new BannerMode();
            bannerMode.pictureKey = new ImageMode(urls[i]);
            videoModeList.add(new NewMainVideoMode("rookiCi" + i, -3).setBannerMode(bannerMode));
        }
        smartLayout.postDelayed(() -> getVideoListRet(videoGroupMode, true), 100);
    }


    //@Override
    public void getVideoListRet(MainLiveVideoGroupMode groupMode, boolean isClear) {
        if (groupMode == null) groupMode = new MainLiveVideoGroupMode();
        List<NewMainVideoMode> list = groupMode.getVideoModeList();
        smartLayout.finishRefresh(50);
        if (!isClear) return;

        //if (isClear) {
        modeList.clear();
        fragmentList.clear();
        horizontalViewPager.removeAllViewsInLayout();
        //}
        for (int i = 0; i < list.size(); i++) {
            NewMainVideoMode videoMode = list.get(i);
            if (hasVideo(videoMode)) continue;
            modeList.add(videoMode);
            BaseFragment fragment = getFragment(videoMode);
            fragmentList.add(fragment);
        }
        pagerAdapter.notifyDataSetChanged();
        drawerViewHolder.notifyDataSetChanged();
    }

    private boolean hasVideo(NewMainVideoMode videoMode) {
        if (videoMode == null) return true;
        for (int i = 0; i < modeList.size(); i++) {
            NewMainVideoMode mode = modeList.get(i);
            if (videoMode.equals(mode)) {
                return true;
            }
        }
        return false;
    }

    private BaseFragment getFragment(NewMainVideoMode videoMode) {
        BaseFragment fragment;
        /*if (videoMode.contentType == 5 || videoMode.contentType == -2) {
            fragment = MiniLiveNoticeFragment.newInstance(videoMode);
        } else if (videoMode.contentType == 1) {
            fragment = MiniLiveRoomFragment.newInstance(videoMode);
        } else if (videoMode.contentType == 4 || videoMode.contentType == -1) {
            fragment = MiniLiveBackPlayFragment.newInstance(videoMode);
        } else {}*/
        fragment = MiniLivePhotoFragment.newInstance(videoMode);

        return fragment;
    }

    /*@Override
    public Object onFragmentCallBack(BaseFragment fragment, int type, Object object) {
        Object obj = null;
        switch (type) {
            case -2://狸猫换太子
                if (isDestroyView) return obj;
                int i = fragmentList.indexOf(fragment);//找太子
                if (i < 0) return obj;//没找到不换了
                if (!(object instanceof NewMainVideoMode)) return obj; //确认下狸猫，发现不是狸猫不换了
                NewMainVideoMode videoMode = (NewMainVideoMode) object;
                BaseFragment f = getFragment(videoMode);//伪装成太子
                if (f == null) return obj;//伪装失败不换了
                fragmentList.add(i, f);//将狸猫塞进床上
                fragmentList.remove(fragment);//抱走太子
                pagerAdapter.notifyDataSetChanged();//换成功，发信号告诉老大
                modeList.remove(i);
                modeList.add(i, videoMode);
                drawerViewHolder.notifyDataSetChanged();
                break;
            case -3: {//询问播放令牌
                if (fragment != null) {
                    int currentItem = horizontalViewPager.getCurrentItem();
                    int index = fragmentList.indexOf(fragment);
                    boolean b = currentItem == index;
                    if (b && isPause) {//不给令牌 还得更改状态
                        obj = false;
                        fragment.setUserVisibleHint(false);
                    } else obj = b;
                }
            }
            break;
            case 111: {
                int index = fragmentList.indexOf(fragment);
                if (index >= 0) {
                    NewMainVideoMode mode = modeList.get(index);
                    List<NewMainVideoMode> list = new ArrayList<>();
                    int idx = 0;
                    for (int j = 0; j < modeList.size(); j++) {
                        NewMainVideoMode videoMode1 = modeList.get(j);
                        if (videoMode1.contentType == -3) continue;
                        list.add(videoMode1);
                        if (mode == videoMode1) idx = list.size() - 1;
                    }
                    VideoRoomPlayActivity.open(getActivity(), list, idx, RoomRequestManage.RequestType.DefaultType_);
                }
            }
            break;
            case 112: {//得到并传递详情数据
                if (object instanceof Object[]) {
                    Object[] objects = (Object[]) object;
                    if (objects.length == 2 && objects[0] instanceof String) {
                        String contentId = (String) objects[0];
                        drawerViewHolder.addDetailsMode(contentId, objects[1]);
                    }
                }
            }
            break;
            case 113: {
                if (fragment != null) fragment.sendMessage(1001, contentOffset);
            }
            break;
        }
        return obj;
    }*/

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 100) {
            if (fragmentList.size() == 0) return;
            int currentItem = horizontalViewPager.getCurrentItem();
            fragmentList.get(currentItem)
                    .onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    @Override
    public void onChangeOpen(boolean open) {
        //if (BuildConfig.DEBUG) return;
        //horizontalViewPager.setScroll(!open);
    }

    @Override
    public void onLayoutDrawerClick(NewMainVideoMode mode) {
        int position = modeList.indexOf(mode);
        if (position < 0) return;
        int currentItem = horizontalViewPager.getCurrentItem();
        if (position == currentItem) return;
        horizontalViewPager.setCurrentItem(position);
    }

    @Override
    public void onContentOffset(float offset) {
        contentOffset = offset;
        final int currentItem = horizontalViewPager.getCurrentItem();
        if (currentItem < 0 || fragmentList == null || currentItem >= fragmentList.size()) return;
        BaseFragment baseFragment = fragmentList.get(currentItem);
        baseFragment.sendMessage(1001, offset);
    }

    /*@Override
    public void onDrawerRoomDetailsRet(NewMainVideoMode videoMode, Object data) {
        //发送至MiniLiveRoomFragment
        int i = modeList.indexOf(videoMode);
        if (i < 0) return;
        BaseFragment baseFragment = fragmentList.get(i);
        baseFragment.sendMessage(1002, data);
    }*/
}
